package com.xiaoxing.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxing.domain.ResponseResult;
import com.xiaoxing.domain.dto.CommentDto;
import com.xiaoxing.domain.dto.TalkDto;
import com.xiaoxing.domain.entity.Talk;
import com.xiaoxing.domain.vo.CommentPageVo;
import com.xiaoxing.service.TalkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @description:
 * @author: lyg
 * @create: 2024-03-06 14:16
 **/
@RestController
@RequestMapping("/talk")
@Api(value = "后台说说接口")
public class TalkController {
    @Autowired
    private TalkService talkService;

    //新增说说
    @PostMapping("/addValue")
    public ResponseResult add(@RequestBody Talk talk){
        return ResponseResult.okResult(talkService.save(talk));
    }

    //删除说说
    @DeleteMapping("/deleteValue")
    public ResponseResult deleteValue(@PathVariable Long id){
        return  ResponseResult.okResult(talkService.removeById(id));
    }

    @PutMapping("/updateValue")
    public ResponseResult updateValue(@RequestBody Talk talk){
        return ResponseResult.okResult(talkService.updateById(talk));
    }

    @ApiOperation("说说分页")
    @PostMapping ("/talkList")
    public ResponseResult getTalkList(@RequestBody TalkDto talkDto){
        LambdaQueryWrapper<Talk> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        if (talkDto.getName() != null && !talkDto.getName().isEmpty()) {
            lambdaQueryWrapper.like(Talk::getName, talkDto.getName());
        }
        if (talkDto.getMessage() != null && !talkDto.getMessage().isEmpty()) {
            lambdaQueryWrapper.like(Talk::getMessage, talkDto.getMessage());
        }
        List<Talk> list = talkService.list(lambdaQueryWrapper);
        int total = list.size(); // 获取总记录数
        // 计算分页起始索引和结束索引
        int startIndex = (talkDto.getPageNum() - 1) * talkDto.getPageSize();
        int endIndex = Math.min(startIndex + talkDto.getPageSize(), total);

        // 截取分页数据
        List<Talk> pageData = list.subList(startIndex, endIndex);

        // 构建返回的分页对象
        Page<Talk> page = new Page<>();
        page.setCurrent(talkDto.getPageNum());
        page.setSize(talkDto.getPageSize());
        page.setRecords(pageData);
        page.setTotal(total);
        return ResponseResult.okResult(page);
    }


}
